from datetime import datetime, timedelta

from fastapi import APIRouter, Depends
from requests import Session

from Util.ActivityUtil import get_detail, get_sign_code, sign_in_out, get_all_sign_activity
from config.Database import get_db
from schemas.SignApplyInfo import SignApplyInfoCreate
from schemas.Submitinfo import SubmitInfoCreate, SubmitSign, SubmitTokenSign
from services.SignApplyInfoServe import SignApplyInfoServe


sign_apply_info_serve = SignApplyInfoServe()



# 根据报名请求信息,, 插入自动报名信息
async def autoSignActivity(submitInfo: SubmitInfoCreate,token:str,user_detail:dict,db: Session = Depends(get_db)):
    if submitInfo.autoSignInTime is not None or submitInfo.autoSignOutTime is not None:
        # 必有一个要自动, 现在获取活动的活动开始时间
        activity_detail = await get_detail(id=submitInfo.ids[0],token=token)
        activity_startTime = activity_detail['startTime'] / 1000.0
        activity_endTime = activity_detail['endTime'] / 1000.0
        nickName =None
        if user_detail is None:
            nickName = "获取用户信息失败"
        else:
            nickName = user_detail.name
        if submitInfo.autoSignInTime is not None:
            #活动开始时间, 加上自动签到时间
            apply_time = datetime.fromtimestamp(activity_startTime) +timedelta(minutes=submitInfo.autoSignInTime)
            # 加入一条自动签到的信息
            sign_apply_info_serve.create(db, SignApplyInfoCreate(username=submitInfo.username, password=submitInfo.password,
                                                                 activityId=str(submitInfo.ids[0]),signType=1,
                                                                 nickName=nickName,
                                                                 activityName=activity_detail['name'],createAt=datetime.now(),
                                                                 signTime=apply_time,remark='准备自动签到'))
        if submitInfo.autoSignOutTime is not None:
            apply_time = datetime.fromtimestamp(activity_endTime) - timedelta(minutes=submitInfo.autoSignOutTime)
            sign_apply_info_serve.create(db, SignApplyInfoCreate(username=submitInfo.username, password=submitInfo.password,
                                                                 activityId=str(submitInfo.ids[0]), signType=2,
                                                                 nickName=nickName,
                                                                 activityName=activity_detail['name'],
                                                                 createAt=datetime.now(),
                                                                 signTime=apply_time, remark='准备自动签退'))
